package com.atguigu.service.impl;

import cn.hutool.core.lang.tree.Tree;
import com.atguigu.dto.system.AssginMenuDto;
import com.atguigu.dto.system.SysMenuDto;
import com.atguigu.entity.system.SysMenu;
import com.atguigu.entity.system.SysUser;
import com.atguigu.exception.ResultException;
import com.atguigu.mapper.SysMenuMapper;
import com.atguigu.mapper.SysRoleMenuMapper;
import com.atguigu.service.SysMenuService;
import com.atguigu.utils.AuthContextUtil;
import com.atguigu.utils.TreeHelper;
import com.atguigu.vo.common.ResultCodeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SysMenuServiceImpl implements SysMenuService {
    @Autowired
    private SysMenuMapper sysMenuMapper;

    @Autowired
    private SysRoleMenuMapper sysRoleMenuMapper;

    @Override
    public void submit(SysMenu sysMenu) {
        sysMenuMapper.submit(sysMenu);
    }

    @Override
    public void remove(Long menuId) {
        Long count = sysMenuMapper.selectChildrenCountById(menuId);
        if (count != 0) {
            throw new ResultException(ResultCodeEnum.NODE_ERROR);
        }
        sysMenuMapper.remove(menuId);
    }

    @Override
    public void update(SysMenu sysMenu) {
        sysMenuMapper.update(sysMenu);
    }

    @Override
    public List<SysMenu> tree(SysMenuDto sysMenuDto) {
        List<SysMenu> menuList = sysMenuMapper.tree(sysMenuDto);
        List<SysMenu> treeMenuList = TreeHelper.build(menuList);
        return treeMenuList;
    }

    @Override
    public List<SysMenu> menus() {
        SysUser sysUser = AuthContextUtil.get();
        Long userId = sysUser.getId();
        List<SysMenu> sysMenus = sysMenuMapper.selectUserMenuByUserId(userId);
        List<SysMenu> treeMenuList = TreeHelper.build(sysMenus);
        return treeMenuList;
    }

    @Override
    public List<Long> roleMenus(Long roleId) {
        sysRoleMenuMapper.findMenuIdListByRoleId(roleId);
        return null;
    }

    @Override
    public void addRoleMenus(AssginMenuDto assginMenuDto) {

        Long roleId = assginMenuDto.getRoleId();
        List<Map<String, Number>> menuIdList = assginMenuDto.getMenuIdList();
        sysRoleMenuMapper.addRoleMenus(roleId, menuIdList);
    }
}
